package morenoapp.components.common;

import java.util.HashSet;
import java.util.Set;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import morenoapp.MorenoApp;
import morenoapp.model.data.MorenoModelFace;

/**
 * Базовая астракнтая модель данных для всех моделей данных таблиц, 
 * работающих с моделью Морено.
 *
 * @author dmitry.mamonov
 */
public abstract class AbstractMorenoTableModel implements TableModel {
    private Set<TableModelListener> listeners = new HashSet<TableModelListener>();

    public AbstractMorenoTableModel() {
        super();
    }


    /* public methods */

    public MorenoModelFace getMorenoModel() {
        return MorenoApp.getApplicationData().getMorenoModelProxy();
    }

    /* TableModel implementation */
    public void addTableModelListener(TableModelListener l) {
        listeners.add(l);
        System.out.println("added to " + getClass().getSimpleName() + " / " + listeners); //NOI18N
    }

    public void removeTableModelListener(TableModelListener l) {
        listeners.remove(l);
        System.out.println("removed from " + getClass().getSimpleName() + " / " + listeners); //NOI18N
    }

    /* inner methods */
    protected void fireTableChanged(TableModelEvent e) {
        System.out.print("fire " + getClass().getSimpleName() + " ["); //NOI18N
        for (TableModelListener l : listeners) {
            System.out.print(l + ","); //NOI18N
            l.tableChanged(e);
        }
        System.out.println("]"); //NOI18N
    }

    protected void checkColumnRange(int columnIndex) throws IllegalArgumentException {
        if (columnIndex < 0 || columnIndex >= getColumnCount()) {
            throw new IllegalArgumentException(columnIndexOutOfBounds(columnIndex));
        }
    }

    protected void checkRange(int rowIndex, int columnIndex) {
        checkRowRange(rowIndex);
        checkColumnRange(columnIndex);
    }

    protected void checkRowRange(int rowIndex) throws IllegalArgumentException {
        if (rowIndex < 0 || rowIndex >= getRowCount()) {
            throw new IllegalArgumentException(rowIndexOutOfBounds(rowIndex));
        }
    }

    protected String columnIndexOutOfBounds(int columnIndex) {
        return "Column index " + columnIndex + " if out of range [0.." + getColumnCount() + ")"; //NOI18N
    }

    protected String rowIndexOutOfBounds(int columnIndex) {
        return "Row index " + columnIndex + " is out of range [0.." + getRowCount() + ")"; //NOI18N
    }
}
